package hw.ats.news.activity.news;

import hw.ats.common.model.Ad;
import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.activity.cmt.CmtAct;
import hw.ats.news.model.Cate;
import hw.ats.news.model.News;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.util.App;
import hw.ats.news.util.DataLoader;

import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.humanwares.ui.tabbar.TabHost;
import com.humanwares.util.DateUtil;
import com.humanwares.util.StringUtil;
import com.humanwares.util.WebUtil;
import com.tattermedia.allthataudio.activities.PlayListActivity;
import com.tattermedia.allthataudio.audio.AudioPlayerManager;
import com.tattermedia.allthataudio.audio.CommonAudioPlayerStatusListener;
import com.tattermedia.allthataudio.audio.IAudioPlayerStatusListener;
import com.tattermedia.allthataudio.audio.PlayListItem;
import com.tattermedia.allthataudio.misc.DebugFlag;
import com.tattermedia.allthataudio.views.AudioPlayerProgressView;

public class ViewAct extends DBAwareActivity {
	private static final String TAG = "ViewArt";
	
	public static final int BOOKMARK_HIGHLIGHT_COLOR = Color.argb(0xff, 0xff, 0x66, 0x99);
	
	private News news = null;
	private TabHost navbar = null;
	private SharedPreferences pref = null;
	
	private Button navCmtBtn = null;
	private Button navBookmarkBtn = null;
	
	private WebView htmlView = null;
	private boolean lastNavView = true;
	
	// audio status listener
	private IAudioPlayerStatusListener mAudioStatusListener;
    
	// 현재 선택된 카테고리
	private Cate cate = null;
	
	private class JavaScriptBridge {
		public void play() {
			AudioPlayerManager.getManager().addToPlayList(news);
			
			try {
				AudioPlayerManager.getManager().playAudioFromUid(news.uid);
				Toast.makeText(ViewAct.this, R.string.audio_now_start_play, Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				Toast.makeText(ViewAct.this, e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			
		}
		
		public void add() {
			boolean retValue = AudioPlayerManager.getManager().addToPlayList(news);
	    	
	    	if (retValue) {
	    		Toast.makeText(ViewAct.this, R.string.audio_playlist_added, Toast.LENGTH_SHORT).show();
	    	} else {
	    		Toast.makeText(ViewAct.this, R.string.audio_playlist_already_exist, Toast.LENGTH_SHORT).show();
	    	}
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        
        String orientationType = pref.getString("pref_screen_rotate", null);
        if ("2".equals(orientationType))
        	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        else if ("1".equals(orientationType))
        	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        else
        	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        
        loadData();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.act_view);
        
		navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB5);
		
		int orientation = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
		if (orientation != 0) {
			navbar.setVisibility(View.INVISIBLE);
		} else if (pref.getBoolean("pref_hide_menu_auto", true)) {
        	navbar.setVisibility(View.INVISIBLE);
        } else {
        	navbar.setVisibility(View.VISIBLE);
        }
		
		lastNavView = navbar.getVisibility() == View.VISIBLE;

		// 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonBackEvent(this);
        
        htmlView = (WebView)findViewById(R.id.view_html);
        htmlView.addJavascriptInterface(new JavaScriptBridge(), "Bridge");
        
        // 댓글화면
        navCmtBtn = (Button)findViewById(R.id.navbar_right_cmt);
        navCmtBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ViewAct.this, CmtAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				
			    startActivityForResult(intent, 1000);
			}
		});
        
//        // 댓글개수
//        navCmtCnt = (TextView)findViewById(R.id.navbar_right_cmt_cnt);
        
        // 북마크화면
        navBookmarkBtn = (Button)findViewById(R.id.navbar_right_bookmark);
        navBookmarkBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!news.favor_flag) {
					new AlertDialog.Builder(ViewAct.this)
					.setTitle(App.APP_TITLE)
					.setMessage("글을 북마크 보관함에 보관하시겠습니까?")
					.setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() {
					    public void onClick(final DialogInterface dialog, final int arg1) {
					    	news.markFavorite(getWritableDatabase(), true);
//					    	navBookmarkBtn.setImageResource(R.drawable.ic_favor_on);
					    	navBookmarkBtn.setTextColor(BOOKMARK_HIGHLIGHT_COLOR);
					    }
					})
					.setNegativeButton(R.string.common_no, new DialogInterface.OnClickListener() {
					    public void onClick(final DialogInterface dialog, final int arg1) {
					    }
					})
					.show();
				} else {
					new AlertDialog.Builder(ViewAct.this)
					.setTitle(App.APP_TITLE)
					.setMessage("글을 북마크 보관함에서 삭제하시겠습니까?")
					.setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() {
					    public void onClick(final DialogInterface dialog, final int arg1) {
					    	news.markFavorite(getWritableDatabase(), false);
//					    	navBookmarkBtn.setImageResource(R.drawable.ic_favor);
					    	navBookmarkBtn.setTextColor(Color.WHITE);
					    }
					})
					.setNegativeButton(R.string.common_no, new DialogInterface.OnClickListener() {
					    public void onClick(final DialogInterface dialog, final int arg1) {
					    }
					})
					.show();
				}
			}
		});
        
        // 공유화면
        final Button navShareBtn = (Button)findViewById(R.id.navbar_right_share);
        navShareBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				String url;
//				if (news.url == null) url = null;
//				else {
//					url = App.NEWS_BODY_XML_URL + news.uid;
//					Log.d("ULR URL", url);
//					url = WebUtil.bitlyShorten(	App.BITLY_USERNAME, App.BIYLY_APIKEY, url);
//				}
				
				String url = news.url == null ? "" : WebUtil.bitlyShorten(
						App.BITLY_USERNAME, App.BIYLY_APIKEY, news.url);
				
				Intent sendIntent = new Intent(Intent.ACTION_SEND);
			    sendIntent.setType("text/plain");
			    sendIntent.putExtra(Intent.EXTRA_SUBJECT, App.APP_TITLE + " 글 공유\n");
			    sendIntent.putExtra(Intent.EXTRA_TEXT, StringUtil.nvl(news.title)+"\n"
			    		+url+"\n["+App.APP_TITLE+"]");
			    startActivity(Intent.createChooser(sendIntent, "글 공유하기"));
			}
		});
        
        // 이전글 화면
        final ImageButton navPrevBtn = (ImageButton)findViewById(R.id.navbar_right_prev);
        navPrevBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				goPrev();
			}
		});
        
        // 다음글 화면
        final ImageButton navNextBtn = (ImageButton)findViewById(R.id.navbar_right_next);
        navNextBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				goNext();
			}
		});
        
        //not used any more 
        //loadDataAsync();
        
        // add audio status listener
        mAudioStatusListener = new CommonAudioPlayerStatusListener(
        		(ImageButton)findViewById(R.id.audio_player_button_play), 
        		(ImageButton)findViewById(R.id.audio_player_button_repeat),
        		(ImageButton)findViewById(R.id.audio_player_button_prev),
        		(ImageButton)findViewById(R.id.audio_player_button_next),
        		(TextView)findViewById(R.id.audio_player_text_subject),
        		(TextView)findViewById(R.id.audio_player_text_time),
        		(AudioPlayerProgressView)findViewById(R.id.audio_player_progress_view));
        
        AudioPlayerManager.getManager().addAudioPlayerStatusListener(mAudioStatusListener);
        
        mAudioStatusListener.onAudioStatusChanged(IAudioPlayerStatusListener.TYPE_COMMON);
        
        loadDataAsyncCmt();
    }
    
    
    private void loadDataAsyncCmt(){

    	
    	
    	if (DebugFlag.isLogEnabled())
    		Log.d(TAG, "loadDataAsync()");

    	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    			
 //   		  	if (DebugFlag.isDebug())
 //   	    		Log.d(TAG, news.body_html);
 //   		  	System.out.println(news.body_html);
    		  	if (news.body_html.equals(""))
    		  	{
    		  		progressDialog = ProgressDialog.show(
    		  				ViewAct.this, App.APP_TITLE, "글을 수신하고 있습니다.", true, false);
    		  	}
    		}

			@Override
			protected Boolean doInBackground(String... params) {
				// 댓글의 개수 확인을 위해 조회시마다 데이터로드
				if (!DataLoader.loadNewsBody(getDBHelper(), news, false))
					return false;
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {
			}

			@Override
			protected void onPostExecute(Boolean result) {
				displayData();
				if (progressDialog != null &&  progressDialog.isShowing())
				progressDialog.dismiss();
				if (result == false) {
					Toast.makeText(ViewAct.this, 
							"글 본문을 수신할 수 없습니다.\n네트워크 접속 상태를 확인하여 주십시오.", 
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
    
    
    private void loadDataAsync() {
    	if (DebugFlag.isLogEnabled())
    		Log.d(TAG, "loadDataAsync()");

    	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	        		ViewAct.this, App.APP_TITLE, "글을 수신하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
				// 댓글의 개수 확인을 위해 조회시마다 데이터로드
				if (!DataLoader.loadNewsBody(getDBHelper(), news, false))
					return false;
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {

			}

			@Override
			protected void onPostExecute(Boolean result) {
				displayData();
				progressDialog.dismiss();
				if (result == false) {
					Toast.makeText(ViewAct.this, 
							"글 본문을 수신할 수 없습니다.\n네트워크 접속 상태를 확인하여 주십시오.", 
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
    
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		
		AudioPlayerManager.getManager().removeAudioPlayerStatusListener(mAudioStatusListener);
		
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
		if (htmlView != null) {
			htmlView.destroy();
		}
	}
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		
		int orientation = ((WindowManager) getSystemService(WINDOW_SERVICE))
				.getDefaultDisplay().getOrientation();
		if (orientation != 0) {
			lastNavView = navbar.getVisibility() == View.VISIBLE;
			navbar.setVisibility(View.INVISIBLE);
		} else {
			navbar.setVisibility(lastNavView ? View.VISIBLE : View.INVISIBLE);
		}
	}
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 댓글에서 돌아올 때 댓글 개수 리프래시
		//if (requestCode == 1000)
		
		// not use anymore ..
		//loadDataAsync();
		
		loadDataAsyncCmt();
		
	}
	
	

	private void displayData() {
//    	navBookmarkBtn.setImageResource(news.favor_flag ? R.drawable.ic_favor_on : R.drawable.ic_favor);
//    	navCmtCnt.setText(String.valueOf(news.cmt_cnt));
		navBookmarkBtn.setTextColor(news.favor_flag ? BOOKMARK_HIGHLIGHT_COLOR : Color.WHITE);
		navCmtBtn.setText("댓글:" + news.cmt_cnt + "개");
    	
        String title = news.title == null ? "" : news.title.replaceAll("%", "%25");
        String author = news.author == null ? "" : news.author.replaceAll("%", "%25");
        String cate_name = news.cate_name == null ? "" : news.cate_name.replaceAll("%", "%25");
        String regdate = DateUtil.stringFromDate("yyyy.MM.dd", news.regdate, null);
    	
        String fontSize = pref.getString("pref_font_size", "18");
        
//        System.out.println(news.body_html); null..
        String htmlbody = news.body_html.replaceAll("%", "%25"); // %를 urlencode
        
        // 사진출력모드를 껐을 경우
        if (!pref.getBoolean("pref_view_thumb", true)) {
        	htmlbody = htmlbody.replaceAll("<(?i)img[ \\\t]+[^>]+>", "");
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append("<html>\n");
        sb.append("<head>\n");
        sb.append("<meta name='viewport' content='target-densitydpi=device-dpi' />\n");
        sb.append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>\n");
        sb.append("<style type='text/css'>\n");
        sb.append("body {margin:0;padding:5px 10px 80px 15px;color:#555555}\n");
        sb.append("div.imageblock {margin:7px 0}\n");
        sb.append("div.center {text-align:center}\n");
        sb.append("body, p, td, a, span {line-height:1.3em;font-size:").append(fontSize).append("pt;}\n");
        sb.append("</style>\n");
        sb.append("</head>\n");
        sb.append("<body>\n");
        sb.append("<table width='100%25' style='background:#eeeeee'>");
        sb.append("<tr><td style='font-size:20pt;font-weight:bold;color:black;padding:5px 0'>").append("&nbsp;&nbsp;" + title).append("</td></tr>");
        sb.append("<tr><td style='font-size:14pt;color:gray'>").append("&nbsp;&nbsp;&nbsp;by " + author + " / " + cate_name + " / " + regdate).append("</td>");
        sb.append("</tr>");
        sb.append("</table>");
        sb.append("<hr style='margin:1px 0 10px 0' size='1' /><div id='BODY_HTML'>");
        sb.append(htmlbody);
        
        // add audio play button
        if (news.mp3_url.trim().length() != 0) {
	        sb.append("\n<br/><br/> <div style=\"text-align:center\"><a onclick=window.Bridge.play();> <img src=\"file:///android_asset/ic_audio_view_button_play.png\"></a>" +
	        		"&nbsp;&nbsp;&nbsp;&nbsp; <a onclick=window.Bridge.add();> <img src=\"file:///android_asset/ic_audio_view_button_add.png\"></a> </div>");
        }
        
        sb.append("\n<br/><br/> <div style=\"text-align:right;font-size:12pt;color:#bbbbbb;\">Copyright by ").append(author).append("</div> ");
        sb.append("\n</div></body>\n");
        sb.append("</html>");
        
        
        
        htmlView.getSettings().setJavaScriptEnabled(true);
        htmlView.getSettings().setPluginsEnabled(true);
        htmlView.getSettings().setBlockNetworkImage(!pref.getBoolean("pref_view_thumb", true));
		htmlView.loadDataWithBaseURL(news.url, sb.toString(), "text/html", "UTF-8", null);

 //       htmlView = (WebView)findViewById(R.id.view_html);
//		htmlView.loadDataWithBaseURL(news.url, sb.toString(), "text/html", "UTF-8", null);
		
	
		// 배너
		final LinearLayout bannerLayer = (LinearLayout)findViewById(R.id.banner_layer);
		final ImageView banner = (ImageView)findViewById(R.id.banner);
		final ImageButton bannerBtn = (ImageButton)findViewById(R.id.banner_btn);
		
		int orientation = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
		if (orientation != 0) {
			if (bannerLayer != null)
				bannerLayer.setVisibility(View.INVISIBLE);
//			
//			
//			
//			
//			return;
		}
		
		final DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		
		if (bannerBtn != null && banner != null) {
			bannerBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (banner.getVisibility() == View.VISIBLE) {
						RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)bannerLayer.getLayoutParams();
						params.height = (int)(22 * dm.density);
						bannerLayer.setLayoutParams(params);
						banner.setVisibility(View.INVISIBLE);
					} else {
						RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)bannerLayer.getLayoutParams();
						params.height = (int)(72 * dm.density);
						bannerLayer.setLayoutParams(params);
						banner.setVisibility(View.VISIBLE);
					}
				}
			});
		}
		
		try {
			final Ad ad = Ad.load(getReadableDatabase());
			if (ad == null) {
				bannerLayer.setVisibility(View.INVISIBLE);
			} else if (banner != null && ad != null) {
				URL imageURL = new URL(ad.image);
				HttpURLConnection conn = (HttpURLConnection)imageURL.openConnection();            
				BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), 10240);
				Bitmap bm = BitmapFactory.decodeStream(bis);
				bis.close();   
				banner.setImageBitmap(bm);
				bannerLayer.setVisibility(View.VISIBLE);
				banner.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ad.url));
						startActivity(intent);
					}
				});
				
				banner.postDelayed(new Runnable() {
					@Override
					public void run() {
						RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)bannerLayer.getLayoutParams();
						params.height = (int)(22 * dm.density);
						bannerLayer.setLayoutParams(params);
						banner.setVisibility(View.INVISIBLE);
					}
				}, 3000);
			}
		} catch (Exception ignored) {
			bannerLayer.setVisibility(View.INVISIBLE);
		}
	
		
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
		int orientation = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
		if (orientation == 0) {
	        int visibility = navbar.getVisibility();
	        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
		}
        return false;
    }
    
    private void loadData() {
    	cate = null;
    	int cid = getIntent().getIntExtra(App.INTENT_EXTRA_CATE_UID, 0);
    	if (cid > 0) {
    		cate = Cate.load(getReadableDatabase(), cid);
    	}
    	
    	int uid = getIntent().getIntExtra(App.INTENT_EXTRA_NEWS_UID, 0);
    	if (uid > 0) {
    		news = News.load(getReadableDatabase(), uid);
    		news.updateBody(getWritableDatabase());
    	}
    }
    
    /**
     * 다음 글
     */
    private void goNext() {
    	int uid = getIntent().getIntExtra(App.INTENT_EXTRA_NEWS_UID, 0);
    	if (uid <= 0)
    		return;
    	
    	String actName = getIntent().getStringExtra(App.INTENT_EXTRA_ACT_NAME);
    	if (actName == null)
    		return;
    	
    	News entry = null;
    	
    	// 추천글
    	if (actName.equals(RecmdAct.class.getName())) {
    		entry = News.nextRecmd(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 최신글
    	else if (actName.equals(RecentAct.class.getName())) {
    		entry = News.next(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 카테고리글
    	else if (actName.equals(CateAct.class.getName())) {
    		entry = News.next(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 사진글
    	else if (actName.equals(PhotoAct.class.getName())) {
    		entry = News.nextPhoto(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 영상글
    	else if (actName.equals(MovieAct.class.getName())) {
    		entry = News.nextMovie(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 검색글
    	else if (actName.equals(SearchAct.class.getName())) {
    		String keyword = getIntent().getStringExtra(App.INTENT_EXTRA_KEYWORD);
    		entry = News.nextSearch(getReadableDatabase(), news.uid, keyword);
    	}
    	
    	// 북마크글
    	else if (actName.equals(BookmarkAct.class.getName())) {
    		entry = News.nextFavor(getReadableDatabase(), news.uid);
    	} 
    	
    	// play list
    	else if (actName.equals(PlayListActivity.class.getName())) {
    		AudioPlayerManager manager = AudioPlayerManager.getManager();
    		PlayListItem item = manager.getPlayListItemFromUid(news.uid);
    		int index = manager.indexOf(item);
    		
    		item = manager.getPlayListItemFromIndex(index + 1);
    		
    		if (item != null) {
    			entry = News.load(getReadableDatabase(), item.getUid());
    		}
    		
    	}
    	
		if (entry == null || entry.uid == news.uid) {
			Toast.makeText(this, "마지막 글 입니다.", Toast.LENGTH_SHORT).show();
			return;
		}
		
		this.news = entry;
		Intent intent = getIntent().putExtra(App.INTENT_EXTRA_NEWS_UID, entry.uid);
		startActivity(intent);
		finish();
		overridePendingTransition(0, 0);
    }
    
    /**
     * 이전 글
     */
    private void goPrev() {
    	int uid = getIntent().getIntExtra(App.INTENT_EXTRA_NEWS_UID, 0);
    	if (uid <= 0)
    		return;
    	
    	String actName = getIntent().getStringExtra(App.INTENT_EXTRA_ACT_NAME);
    	if (DebugFlag.isLogEnabled())
    		Log.d(TAG, "goPrev.actName="+actName);
    	if (actName == null)
    		return;
    	
    	News entry = null;
    	
    	// 추천글
    	if (actName.equals(RecmdAct.class.getName())) {
    		entry = News.prevRecmd(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 최신글
    	else if (actName.equals(RecentAct.class.getName())) {
    		entry = News.prev(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 카테고리글
    	else if (actName.equals(CateAct.class.getName())) {
    		entry = News.prev(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 사진글
    	else if (actName.equals(PhotoAct.class.getName())) {
    		entry = News.prevPhoto(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 영상글
    	else if (actName.equals(MovieAct.class.getName())) {
    		entry = News.prevMovie(getReadableDatabase(), news.uid, cate == null ? 0 : cate.uid);
    	}
    	
    	// 검색글
    	else if (actName.equals(SearchAct.class.getName())) {
    		String keyword = getIntent().getStringExtra(App.INTENT_EXTRA_KEYWORD);
    		entry = News.prevSearch(getReadableDatabase(), news.uid, keyword);
    	}
    	
    	// 북마크글
    	else if (actName.equals(BookmarkAct.class.getName())) {
    		entry = News.prevFavor(getReadableDatabase(), news.uid);
    	}
    	
    	// play list
    	else if (actName.equals(PlayListActivity.class.getName())) {
    		AudioPlayerManager manager = AudioPlayerManager.getManager();
    		PlayListItem item = manager.getPlayListItemFromUid(news.uid);
    		int index = manager.indexOf(item);
    		
    		item = manager.getPlayListItemFromIndex(index - 1);
    		
    		if (item != null) {
    			entry = News.load(getReadableDatabase(), item.getUid());
    		}
    		
    	}
    	
		if (entry == null || entry.uid == news.uid) {
			Toast.makeText(this, "처음 글 입니다.", Toast.LENGTH_SHORT).show();
			return;
		}
		
		this.news = entry;
		Intent intent = getIntent().putExtra(App.INTENT_EXTRA_NEWS_UID, entry.uid);
		startActivity(intent);
		finish();
		overridePendingTransition(0, 0);
    }
}
